package com.feityz.handler.ptws;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.model.ProcessInstance;
import com.bstek.uflo.process.handler.AssignmentHandler;
import com.bstek.uflo.process.node.TaskNode;
import com.feityz.system.entity.Role;
import com.feityz.system.entity.RoleArea;
import com.feityz.system.entity.RoleAreaUser;
import com.feityz.system.service.IRoleAreaService;
import com.feityz.system.service.IRoleAreaUserService;
import com.feityz.system.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * PTW签收确认
 */
@Component
public class PtwSureAssignmentHandler implements AssignmentHandler {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IRoleAreaService roleAreaService;
    @Autowired
    private IRoleAreaUserService roleAreaUserService;
    @Override
    public Collection<String> handle(TaskNode taskNode, ProcessInstance processInstance, Context context) {

        String roleName = "PTW签发";

        Role role = roleService.lambdaQuery().eq(Role::getRoleName,roleName).one();

        String promoter = processInstance.getPromoter();

        List<String> users = new ArrayList<>();

        Object areas = context.getProcessService().getProcessVariable("AREA", processInstance.getId());

        Assert.isTrue(areas!=null,"请传入AREA参数");

        String[] area = areas.toString().split(",");

        List<Long> roleareas = roleAreaService.lambdaQuery()
                .in(RoleArea::getArea, area)
                .eq(RoleArea::getRoleId,role.getId())
                .list()
                .stream().map(e -> e.getId()).collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(roleareas)) {

            List<RoleAreaUser> roleAreaUsers = roleAreaUserService.lambdaQuery().
                    in(RoleAreaUser::getRoleAreaId, roleareas).list();
            if(CollectionUtil.isNotEmpty(roleAreaUsers)) {
                users.addAll(
                        roleAreaUsers
                                .stream().filter(e -> !e.equals(promoter))
                                .map(e -> e.getUserId().toString()).collect(Collectors.toList()));
            }
        }
        users.add(processInstance.getPromoter());
        return users;
    }

    @Override
    public String desc() {
        return "工程单位签收确认";
    }
}
